package com.treasure.mall.zbqmallmanager.controller;

import com.treasure.mall.biz.dto.condition.AdvanceLogSearchCondition;
import com.treasure.mall.biz.dto.condition.UserSearchCondition;
import com.treasure.mall.biz.dto.user.ModifyBalanceDTO;
import com.treasure.mall.biz.entity.auth.SystemManager;
import com.treasure.mall.biz.entity.log.AdvanceLogPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.log.AdvanceLogService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import com.treasure.mall.zbq.common.base.TwoTuple;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.base.CodeDescEnumHelper;
import com.treasure.mall.zbq.common.ienum.log.AdvanceLogType;
import com.treasure.mall.zbq.common.ienum.log.LogDataType;
import com.treasure.mall.zbq.common.ienum.user.UserEnums;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallmanager.controller
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/12 13:39
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.zbqmallmanager.controller Inc. All rights reserved.
 */
@Controller
@RequestMapping("/user")
@PreAuthorize("hasAnyRole('ADMIN')")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private AdvanceLogService advanceLogService;


    /**
     * 用户列表
     *
     * @param condition
     * @param type      0 普通用户 1会员用户
     * @param pageIndex
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@ModelAttribute("condition") UserSearchCondition condition,
                       @RequestParam(required = false, defaultValue = "0") Integer type,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex, Model model) {


        UserEnums.UserType userTypeEnum = CodeDescEnumHelper.getEnumTypeByCode(UserEnums.UserType.class, type);
        condition.setUserType(userTypeEnum);
        Page<UserPO> userPOS = userService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", userPOS.getTotalElements());
        model.addAttribute("totalPages", userPOS.getTotalPages());


        userPOS.getContent().forEach(item -> {
            if (item.isExistParent()) {
                item.setGuider(userService.findByParentId(item.getParentId()));
            }
        });

        model.addAttribute("list", userPOS.getContent());
        model.addAttribute("type", type);
        return "user/user_list";
    }


    /**
     * 用户详情
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(@ModelAttribute("userId") Long userId, Model model) {
        UserPO userPO = userService.findById(userId);
        model.addAttribute("user", userPO);
        model.addAttribute("parentList", userService.getSuperiorUserList(userId));
        return "user/user_detail";
    }


    /**
     * 修改可用余额
     *
     * @param modifyBalanceDTO
     * @param manager
     * @return
     */
    @RequestMapping(value = "/modifyBalance", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult modifyBalance(ModifyBalanceDTO modifyBalanceDTO, @AuthenticationPrincipal SystemManager manager) {
        modifyBalanceDTO.setLogType(AdvanceLogType.MANUAL);
        modifyBalanceDTO.setOpId(manager.getUserId());
        modifyBalanceDTO.setOpName(manager.getUsername());
        if (StringUtils.isEmpty(modifyBalanceDTO.getRemark())) {
            modifyBalanceDTO.setRemark("系统处理");
        }
        userService.modifyBalance(modifyBalanceDTO);

        return ApiResult.resultWith(ResultCodeEnum.SUCCESS);
    }

    /**
     * 人物关系
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail/tree", method = RequestMethod.GET)
    public String tree(Long userId, Model model) {
        UserPO userPO = userService.findById(userId);
        if (userPO.getParentId() > 0) {
            userPO.setGuider(userService.findById(userPO.getParentId()));
        }
        UserSearchCondition condition = new UserSearchCondition();
        condition.setParentId(userId);
        model.addAttribute("user", userPO);
        model.addAttribute("children", userService.findChildren(condition));
        model.addAttribute("teamSummary", userService.inviteSummary(userId, true));


        return "user/user_detail_tree";
    }

    /**
     * 余额明细
     *
     * @param type      1：余额明细，2：待入账明细
     * @param condition
     * @param pageIndex
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail/advanceLog/{type}", method = RequestMethod.GET)
    public String advanceLogs(@PathVariable("type") int type,
                              @ModelAttribute("condition") AdvanceLogSearchCondition condition,
                              @RequestParam(required = false, defaultValue = "1") int pageIndex, Model model) {
        condition.setDataType(type == 1 ? LogDataType.BALANCE : LogDataType.WAIT_BALANCE);
        Page<AdvanceLogPO> advanceLogPOS = advanceLogService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", advanceLogPOS.getTotalElements());
        model.addAttribute("totalPages", advanceLogPOS.getTotalPages());
        model.addAttribute("logs", advanceLogPOS.getContent());
        model.addAttribute("user", userService.findById(condition.getUserId()));
        model.addAttribute("type", type);

        return "user/user_detail_advance_log";
    }


    /**
     * 下级列表
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/children", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult children(@ModelAttribute("userId") long userId) {
        UserPO userPO = userService.findById(userId);

        UserSearchCondition condition = new UserSearchCondition();
        condition.setParentId(userId);

        List<UserPO> userTreeVOS = userService.findChildren(condition);
        return ApiResult.resultWith(ResultCodeEnum.SUCCESS, userTreeVOS);
    }


    /***
     * 变更上线
     *
     * @param userId        用户id
     * @param newParentName 目标上线用户名
     * @return 结果
     */
    @RequestMapping(value = "/changeParent", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult changeParent(@ModelAttribute("userId") long userId,
                                  @RequestParam(required = false, defaultValue = "0") String newParentName,
                                  @AuthenticationPrincipal SystemManager manager) {
        UserPO user = userService.findById(userId);
        UserPO parent = userService.findByUsername(newParentName);
        TwoTuple<Boolean, String> result = userService.changeParent(user, parent, manager);
        if (result.first) {
            return ApiResult.resultWith(ResultCodeEnum.SUCCESS);
        }
        return ApiResult.errorWith(ResultCodeEnum.ERROR, result.second);
    }
}
